<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAdd">创建资源分类</el-button>

    <el-table :data="resourceCategoryList" style="width: 100%;margin-top:30px;" border>
      <el-table-column 
        prop="name" 
        align="center" 
        label="资源分类名称">
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑资源分类':'新建资源分类'">
      <el-form :model="resourceCategory" label-width="80px" label-position="left">
        <el-form-item label="名称">
          <el-input v-model="resourceCategory.name" placeholder="Resource Category Name" />
        </el-form-item>

      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getRoutes, getRoles, addRole, deleteRole, updateRole } from '@/api/role'
import { getResourceCategerys, addResourceCategery, updateResourceCategery, delResourceCategery } from '@/api/permission'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  data() {
    return {
      resourceCategory: {
        
      },
      routes: [],
      resourceCategoryList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      }
    }
  },
  computed: {
    // routesData() {
    //   return this.routes
    // }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getResourceCategerys()
    // this.getRoles()
  },
  methods: {
    async getResourceCategerys() {
      const res = await getResourceCategerys()
      // this.serviceRoutes = res.data
      this.resourceCategoryList = res.data
    },
    async getRoles() {
      const res = await getRoles()
      this.rolesList = res.data
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAdd() {
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      console.log(scope)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.resourceCategory = deepClone(scope.row)
    },
    handleDelete(scope) {
      this.$confirm('确认删除资源分类:'+scope.row.name+'?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async() => {
          await delResourceCategery(scope.row.id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getResourceCategerys()
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });    
      })
    },
    // generateTree(routes, basePath = '/', checkedKeys) {
    //   const res = []

    //   for (const route of routes) {
    //     const routePath = path.resolve(basePath, route.path)

    //     // recursive child routes
    //     if (route.children) {
    //       route.children = this.generateTree(route.children, routePath, checkedKeys)
    //     }

    //     if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
    //       res.push(route)
    //     }
    //   }
    //   return res
    // },
    async confirmSubmit() {
      const isEdit = this.dialogType === 'edit'

      if (isEdit) {
        const res = updateResourceCategery(this.resourceCategory)
        console.log("updateResourceCategery response ",res)
        this.$message({
          message: '更新资源分类成功',
          type: 'success'
        });
      } else {
        const res = addResourceCategery(this.resourceCategory)
        console.log("addResourceCategery response ",res)
        this.$message({
          message: '创建资源分类成功',
          type: 'success'
        });
      }

      this.dialogVisible = false
      this.getResourceCategerys()
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
